import {socketToken, socketBaseUri} from '@/config/default/setting.config'
import {message} from "ant-design-vue";

export default {
  data() {
    return {
      websock: null,
      fieldNameArr: [], //订阅的属性
    }
  },
  methods: {
    //*
    // socket method
    // */
    initWebSocket() {
      if (typeof WebSocket === "undefined") {
        message.error("浏览器不支持socket")
        return;
      } else {
        if(this.websock != null) {
          this.websock.close()
        }
        let u = encodeURI(socketToken);
        let p = this.fieldNameArr.join(',');
        let url = `${socketBaseUri}?devCode=${this.devData.devCode}&param=${p}&Authorization=${u}`
        // 打开一个websocket
        this.websock = new WebSocket(url);
        // 建立连接
        this.websock.onopen = this.websocketonopen;
        // 客户端接收服务端返回的数据
        this.websock.onmessage = this.websocketonmessage;
        // 发生错误时
        this.websock.onerror = this.websocketonerror
        // 关闭连接
        this.websock.onclose = this.websocketclose
      }
    },
    websocketonopen(){
      console.log("socket连接成功")
    },
    // 连接建立失败重连
    websocketonerror(){
      message.error("链接错误")
      this.initWebSocket();
    },
    // 数据接收
    // websocketonmessage(e){
    //   const data = JSON.parse(e.data);
    //   this.showBoard(data)
    // },
    // 数据发送
    websocketsend(Data){
      this.websock.send(Data);
    },
    // 关闭
    websocketclose(e){
      console.log('WebSocket 断开连接',e);
    },
  },
  destroyed() {
    //离开路由之后断开 websocket 连接
    this.websock.close();
  }
}
